package com.suse.service.community.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HtmlUtil;
import com.suse.common.config.response.ApiException;
import com.suse.common.util.extra.DesensitizationUtil;
import com.suse.service.community.constant.EntityTypeConstant;
import com.suse.service.community.entity.Comment;
import com.suse.service.community.mapper.CommentMapper;
import com.suse.service.community.service.CommentService;
import com.suse.service.community.service.DiscussPostService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 评论业务实现类
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-31 20:30
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private DiscussPostService discussPostService;

    @Override
    public List<Comment> getListByEntity(int entityType, int entityId, int offset, int limit) {
        return commentMapper.selectListByEntity(entityType,entityId,offset,limit);
    }

    @Override
    public int getTotalByEntity(int entityType, int entityId) {
        return commentMapper.selectTotalByEntity(entityType,entityId);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public boolean save(Comment comment) {
        if (ObjectUtil.isNull(comment)) {
            return false;
        }
        // 添加评论
        comment.setContent(HtmlUtil.escape(comment.getContent()));
        comment.setContent(DesensitizationUtil.desensitize(comment.getContent()));
        comment.setCreateTime(new Date());
        int row = commentMapper.insert(comment);
        if (row != 1) {
            throw new ApiException("添加失败！");
        }
        // 更新帖子评论数
        if (comment.getEntityType() == EntityTypeConstant.POST) {
            int total = commentMapper.selectTotalByEntity(comment.getEntityType(), comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(),total + 1);
        }
        return true;
    }

}
